package cn.krui.helper.filter;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.web.servlet.FilterRegistrationBean;
import org.springframework.context.ApplicationContext;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import cn.krui.helper.tools.RedisUtils;

import java.util.ArrayList;
import java.util.List;
import java.util.stream.Collectors;

import javax.servlet.DispatcherType;

/**
 * @author zc
 * 资源过滤器，用于处理登录凭证
 */
@Configuration
public class WebFilterConfig {
    @Autowired
    private RedisUtils rUtils;
    @Autowired
    private ApplicationContext applicationAware;

    @Bean
    FilterRegistrationBean<TokenFilter> tokenFilter() {
        // 扫描ITokenFilterSetting的所有实现
        List<String> EXCEPTION_URI_LIST = new ArrayList<>();
        List<String> EXCEPTION_TOKEN_URI = new ArrayList<>();
        String[] result = applicationAware.getBeanNamesForType(ITokenFilterSetting.class);
        for (String string : result) {
            ITokenFilterSetting get = applicationAware.getBean(string,ITokenFilterSetting.class);
            List<String> getlist1 = get.EXCEPTION_URI();
            if (getlist1 != null) {
                EXCEPTION_URI_LIST.addAll(getlist1);
            }
            List<String> getlist2 = get.EXCEPTION_TOKEN_URI();
            if (getlist2 != null) {
                EXCEPTION_TOKEN_URI.addAll(getlist2);
            }
            EXCEPTION_URI_LIST = EXCEPTION_URI_LIST.stream().distinct().collect(Collectors.toList());
            EXCEPTION_TOKEN_URI = EXCEPTION_TOKEN_URI.stream().distinct().collect(Collectors.toList());
        }

        FilterRegistrationBean<TokenFilter> filterReg = new FilterRegistrationBean<TokenFilter>(new TokenFilter(rUtils));
        //优先级
        filterReg.setOrder(70);
        filterReg.setDispatcherTypes(DispatcherType.REQUEST);
        filterReg.addUrlPatterns("/*");
        //配置不验证
        filterReg.addInitParameter("EXCEPTION_URI",String.join(",", EXCEPTION_URI_LIST));
        //配置只验证token不验证权限
        filterReg.addInitParameter("EXCEPTION_TOKEN_URI",String.join(",", EXCEPTION_TOKEN_URI));
        //其他的需要验证权限，根据角色权限验证
        filterReg.setName("tokenfilter");
        return filterReg;
    } 
}